﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

namespace MyFramework.Common
{
    /// <summary>
    /// custom property collection
    /// </summary>
    public class CustomPropertyCollection : ObservableCollection<CustomProperty>
    {
        /// <summary>
        /// Gets the <see cref="CustomProperty"/> with the specified name.
        /// </summary>
        /// <value>
        /// The <see cref="CustomProperty"/>.
        /// </value>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public CustomProperty this[string name]
        {
            get { return this.FirstOrDefault(p => p.Name == name); }
        }

        /// <summary>
        /// Raises the <see cref="E:CollectionChanged" /> event.
        /// </summary>
        /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
            if (e.NewItems != null)
            {
                foreach (CustomProperty item in e.NewItems)
                {
                    item.PropertyChanged += CustomProperty_PropertyChanged;
                }
            }
            if (e.OldItems != null)
            {
                foreach (CustomProperty item in e.OldItems)
                {
                    item.PropertyChanged -= CustomProperty_PropertyChanged;
                }
            }
        }

        /// <summary>
        /// Handles the PropertyChanged event of the CustomProperty control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        private void CustomProperty_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
#if(!SILVERLIGHT)
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender));
#else
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, -1));
#endif
        }

        /// <summary>
        /// Checks the value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name">The name.</param>
        /// <param name="valueFunc">The value func.</param>
        /// <returns></returns>
        public bool CheckValue<T>(string name, Func<T, bool> valueFunc)
        {
            return this.Any(p => p.Name == name && valueFunc(p.GetValue<T>()));
        }
    }
}
